#-*- coding:utf-8 -*-
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex

class prpcrypt():
    def __init__(self, key):
        self.key = self.key_length(key)
        self.mode = AES.MODE_CBC

    def key_length(self,data):
        length = 16
        count = len(data)
        add = length - (count % length)

        data = data + ('\0' * add)
        print data
        return data

    # 加密函数，如果text不是16的倍数【加密文本text必须为16的倍数！】，那就补足为16的倍数
    def encrypt(self, text):
        cryptor = AES.new(self.key, self.mode, self.key)
        textadd = self.key_length(text)
        return b2a_hex(cryptor.encrypt(textadd))

    # 解密后，去掉补足的空格用strip() 去掉
    def decrypt(self, text):
        cryptor = AES.new(self.key, self.mode, self.key)
        plain_text = cryptor.decrypt(a2b_hex(text))
        return plain_text.rstrip('\0')


if __name__ == '__main__':
    while True:
        key = raw_input("please input you key[q:quit]: ")
        if key == "":
            print "key can't be empty!"
        elif key == "q":
            exit(0)
        else:
            ende = prpcrypt(key)
            entype = raw_input('en or de: ')
            if entype == "en":
                passwd = raw_input('please input your pass: ')
                print ende.encrypt(passwd)
            elif entype == 'de':
                passwd = raw_input('please input your pass: ')
                print ende.decrypt(passwd)
